/*
 * polynomial.cpp
 *
 *  Created on: Jun 22, 2011
 *      Author: Gilad & Yotam
 */

#include "polynomial.h"
#include "matrix.h"
#include "mtm.h"


Matrix Polynomial::matrixPower(const Matrix& matrix, int power) {
	/*
	 *  this method have a very specific use, which-in the power is auto generated
	 *  thats why we may assume power >= 0.
	 */
	if (power == 0) {
		return Matrix::createUnit(matrix.rows());
	}
	Matrix newMatrix(matrix);
	for (int i = 1; i < power; ++i) {
		newMatrix *= matrix;
	}
	return newMatrix;
}

Polynomial::Polynomial(int id, int priority, const Matrix& a, const Matrix& b) :
	Job(id, priority, a, b) {
}

Matrix Polynomial::execute() {
	try {
		if ((b.columns() != 1) || (a.rows() != a.columns())) {
			throw Job::JobFailed();
		}
		Matrix solution = matrixPower(a, 0);
		solution = solution * b(1, 1);
		for (int i = 2; i <= b.rows(); ++i) {
			solution += matrixPower(a, i - 1) * b(i, 1);
		}
		return solution;
	} catch (MatrixExceptions::MatrixException&) {
		throw Job::JobFailed();
	}
}
